package wx.controls
{

	import flash.events.Event;
	import flash.events.KeyboardEvent;
	import flash.ui.Keyboard;
	
	import wx.core.SettingCache;
	
	public class View extends ContainerBase
	{
		
		private var _actionBar:ActionBar;
		
		protected var backHandler:Function;
		protected var menuHandler:Function;
		protected var searchHandler:Function;
		
		public function View()
		{
			super();
			
			var content:Scroller = new Scroller();
			content.direction = Scroller.VERTICAL;
			contentGroup =  content;
			updateContent();
			
			addEventListener(Event.ADDED_TO_STAGE,function():void{
				removeEventListener(Event.ADDED_TO_STAGE,arguments.callee);	
				bindEvent();
			});
		}

		public function get actionBar():ActionBar
		{
			return _actionBar;
		}

		public function set actionBar(value:ActionBar):void
		{
			if(_actionBar!=value){
				_actionBar = value;
				overlay = value;
				updateOverlay();
				resizeContentHeight();
			}
		}
		
		private function resizeContentHeight():void{
			contentGroup.y = overlay.height;
			contentGroup.height = SettingCache.mainHeight - overlay.height;
		}
		
		private function bindEvent():void{
			stage.addEventListener(Event.RESIZE,onResize);
			addEventListener(KeyboardEvent.KEY_DOWN,onKeyHandler);
		}
		
		private function unbindEvent():void{
			stage.removeEventListener(Event.RESIZE,onResize);
			removeEventListener(KeyboardEvent.KEY_DOWN,onKeyHandler);
		}
		
		private function onResize(e:Event):void{
			if(contentGroup.width != SettingCache.mainWidth){
				contentGroup.width = SettingCache.mainWidth;
				_actionBar.width =  SettingCache.mainWidth;
			}
			if(contentGroup.height != SettingCache.mainHeight){
				contentGroup.height = SettingCache.mainHeight;
				resizeContentHeight();
			}
		}		
		
		private function onKeyHandler(e:KeyboardEvent):void{
			if(this.backHandler != null &&
				Object(Keyboard).hasOwnProperty("BACK") &&
				e.keyCode == Keyboard["BACK"])
			{
				e.stopImmediatePropagation();
				e.preventDefault();
				this.backHandler();
			}
			
			if(this.menuHandler != null &&
				Object(Keyboard).hasOwnProperty("MENU") &&
				e.keyCode == Keyboard["MENU"])
			{
				e.preventDefault();
				this.menuHandler();
			}
			
			if(this.searchHandler != null &&
				Object(Keyboard).hasOwnProperty("SEARCH") &&
				e.keyCode == Keyboard["SEARCH"])
			{
				e.preventDefault();
				this.searchHandler();
			}
		}
		
		override protected function dispose():void{
			unbindEvent();
		}
		

	}
}